package stu.khy.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import stu.khy.dao.ClaimVoucherDao;

import stu.khy.entity.ClaimVoucher;
import stu.khy.service.ClaimVoucherService;
import stu.khy.util.PaginationSupport;
@Service
public class ClaimVoucherServiceImpl implements ClaimVoucherService {
   @Resource
	private ClaimVoucherDao claimVoucherDao;
   
	
	@Override
	public void saveClaimVoucher(ClaimVoucher claimVoucher) {
		//创建时间
		claimVoucher.setCreateTime(new Date());
		claimVoucher.setModifyTime(claimVoucher.getCreateTime());
		claimVoucherDao.save2(claimVoucher);
	}

	@Override
	public PaginationSupport<ClaimVoucher> getClaimVoucherPage(String createSn, String status, Date startDate,
			Date endDate, Integer pageNo, Integer pageSize) {
		  
		PaginationSupport<ClaimVoucher> result =new PaginationSupport<ClaimVoucher>();
		if(pageNo > 0) {
			
			result.setCurrPageNo(pageNo);
		}
		if(pageSize > 0) {
			result.setPageSize(pageSize);
		}
		StringBuilder hqlBuilder=new StringBuilder("from ClaimVoucher where creator.sn=?");
		List<Object> values=new ArrayList<>();
		values.add(createSn);
		if(status !=null && status.length() !=0) {
			hqlBuilder.append(" and status = ?");
			values.add(status);
		}
		if(startDate !=null) {
			hqlBuilder.append(" and createTime >= ?");
			values.add(startDate);
		}
		if(endDate !=null) {
			hqlBuilder.append(" and createTime <= ?");
			Calendar oneDayLater=Calendar.getInstance();
			oneDayLater.setTime(endDate);
			oneDayLater.add(Calendar.DAY_OF_MONTH,1);
			values.add(oneDayLater.getTime());
		}
		int count=claimVoucherDao.getTotalCount(hqlBuilder.toString(), values.toArray()).intValue();
		result.setTotalCount(count);
		if(count>0) {
			int pageCount =(count +result.getPageSize()-1)/result.getPageSize();
		    result.setTotalPageCount(pageCount);
		    if(result.getCurrPageNo()>pageCount) {
		    	result.setCurrPageNo(pageCount);
		    }
		    if(status ==null || status.length() == 0) {
		    	hqlBuilder.append(" order by status.createTime desc");
		    }else {
		    	hqlBuilder.append(" order by createTime desc");
		    }
		    claimVoucherDao.findForPage(hqlBuilder.toString(), result.getCurrPageNo(), result.getPageSize(),values.toArray());
		 
		}
		return result;
	}

	@Override
	public ClaimVoucher findClaimVoucherById(Long id) {
		
		return claimVoucherDao.findClaimVoucherById(id);
	}

	@Override
	public void updateClaimVoucher(ClaimVoucher claimVoucher) {
		
		claimVoucherDao.update(claimVoucher);
	}

}
